package logic

import (
	"MyBlogv2/Servers/Article/article"
	"MyBlogv2/Servers/Article/internal/svc"
	"MyBlogv2/blog-common/HttpCode"
	define2 "MyBlogv2/blog-common/define"
	"MyBlogv2/blog-common/helper"
	"MyBlogv2/blog-common/models"
	"context"
	"github.com/jinzhu/copier"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetArticlePageListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetArticlePageListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetArticlePageListLogic {
	return &GetArticlePageListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetArticlePageListLogic) GetArticlePageList(in *Article.ArticleRequest) (*Article.GetArticlePageListResponse, error) {
	pageNum := int(in.PageNum)
	pageSize := int(in.PageSize)
	var articleVo []models.ArticleVo
	var total int64
	models.Db.Model(new(models.ArticleVo)).
		Table("t_article a").
		Select("a.*,c.category_name as category_name").
		Joins("left join t_category c on a.category_id = c.id").
		Where("a.status = ?", define2.PUBLIC_ARTICLE).
		Count(&total).
		Order("a.created_at desc").
		Offset((pageNum - 1) * pageSize).
		Limit(pageSize).
		Find(&articleVo)
	for i, v := range articleVo {
		var tags []string
		models.Db.Model(new(models.ArticleTag)).
			Table("t_article_tag at").
			Select("t.tag_name").
			Joins("left join t_tag t on at.tag_id = t.id").
			Where("at.article_id = ?", v.Id).
			Find(&tags)
		articleVo[i].Tags = tags
	}
	var articleVoListResponse []*Article.ArticleVo
	copier.Copy(&articleVoListResponse, &articleVo)
	for i, v := range articleVo {
		articleVoListResponse[i].CreateTime = helper.MyTimeToTimestamp(v.CreateTime)
		articleVoListResponse[i].UpdateTime = helper.MyTimeToTimestamp(v.UpdateTime)
	}
	return &Article.GetArticlePageListResponse{
		Code:  int64(HttpCode.SUCCESS),
		Data:  articleVoListResponse,
		Total: total,
	}, nil
}
